package com.songxh.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.songxh.dto.SetmealDto;
import com.songxh.mapper.SetmealMapper;
import com.songxh.pojo.Setmeal;
import com.songxh.pojo.SetmealDish;
import com.songxh.service.SetmealDishService;
import com.songxh.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author songxh
 * @create 2022-04-24-19:23
 */
@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;

    /**
     * 添加套餐的业务
     * @param setmealDto
     */
    @Override
    public void saveWithDish(SetmealDto setmealDto) {
        //将setmealDto当中的基本信息保存到Setmeal中
        this.save(setmealDto);
        //将菜品信息保存到SetmealDishService
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        //因为setSetmealId的值为空，所以需要在setmealDto获取然后赋值给它
        for (SetmealDish setmealDish : setmealDishes) {
            setmealDish.setSetmealId(setmealDto.getId());
        }
        setmealDishService.saveBatch(setmealDishes);
    }


    /**
     * 根据id来查询套餐内容，包括套餐中的菜品
     * @param id
     * @return
     */
    @Override
    public SetmealDto getByIdWithDish(long id) {
        //在SetmealDish表当中根据id来查询其内容
        QueryWrapper<SetmealDish> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("setmeal_id",id);
        List<SetmealDish> list = setmealDishService.list(queryWrapper);

        SetmealDto setmealDto = new SetmealDto();

        //获取套餐基本信息
        Setmeal setmeal = this.getById(id);
        //将套餐基本信息拷贝到setmealDto中
        BeanUtils.copyProperties(setmeal,setmealDto);
        //设置setmealDto中的SetmealDishes属性
        setmealDto.setSetmealDishes(list);

        return setmealDto;
    }

    /**
     * 修改套餐数据
     * @param setmealDto
     */
    @Override
    public void updateWithDish(SetmealDto setmealDto) {
        //获取id
        Long id = setmealDto.getId();
        QueryWrapper<SetmealDish> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("setmeal_id",id);
        //将菜品删除
        setmealDishService.remove(queryWrapper);

        //将setmealDto的菜品信息传入
        List<SetmealDish> dishList = setmealDto.getSetmealDishes();
        //给每一个菜品赋值id
        for (SetmealDish dish : dishList) {
            dish.setSetmealId(id);
        }

        //保存内容
        setmealDishService.saveBatch(dishList);
        //更新setmeal表
        this.updateById(setmealDto);
    }
}
